﻿// Type: System.Windows.Application
// Assembly: System.Windows, Version=5.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
// Assembly location: c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v5.0\System.Windows.dll

using MS.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Security;
using System.Text;
using System.Windows.Hosting;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Resources;

namespace System.Windows
{
  public class Application : IManagedPeer, IManagedPeerBase, INativeCoreTypeWrapper
  {
    private static readonly DependencyProperty ApplicationStartedProperty = DependencyProperty.RegisterCoreProperty(10110U, typeof (bool));
    private static readonly DependencyProperty ResourcesProperty = DependencyProperty.RegisterCoreProperty(10108U, typeof (ResourceDictionary));
    private static readonly DependencyProperty InstallStateProperty = DependencyProperty.RegisterCoreProperty(10107U, typeof (InstallState));
    private static readonly DependencyProperty IsRunningOutOfBrowserProperty = DependencyProperty.RegisterCoreProperty(10109U, typeof (bool));
    private static Application _current = (Application) null;
    private const string COMPONENT = ";component";
    private const string IN_BROWSER_APP_DATA_PATH_SUFFIX = "{0}Microsoft{0}Silverlight{0}InBrowser";
    private const string IN_BROWSER_JIT_PROFILE_DIR_NAME = "Profiles";
    private const int IN_BROWSER_JIT_PROFILE_MAX = 500;
    private const string JIT_PROFILE_EXTENSION = ".profile";
    private const string JIT_PROFILE_NAME = "Jit{0}{1}.profile";
    private const int ENABLE_JIT_THREASHOLD = 500000;
    private SilverlightHost _host;
    internal EventHandler<ApplicationUnhandledExceptionEventArgs> _appUnhandledException;
    private NativeObjectSafeHandle m_nativePtr;
    private CoreTypeEventHelper _coreTypeEventHelper;
    internal bool? _allowNavigation;
    private UIElement _rootVisual;
    private bool _hasElevatedPermissions;
    private Dictionary<IManagedPeerBase, object> _treeChildren;
    private ApplicationLifetimeObjectsCollection _collection;
    private Window _mainWindow;
    private WindowCollection _windows;

    IntPtr IManagedPeerBase.NativeObject
    {
      [SecurityCritical] get
      {
        if (this.m_nativePtr == null)
          return IntPtr.Zero;
        else
          return this.m_nativePtr.NativeObject;
      }
    }

    public ResourceDictionary Resources
    {
      get
      {
        return (ResourceDictionary) XcpImports.GetValue((IManagedPeerBase) this, Application.ResourcesProperty);
      }
      set
      {
        XcpImports.SetValue((IManagedPeerBase) this, Application.ResourcesProperty, (DependencyObject) value);
      }
    }

    public UIElement RootVisual
    {
      get
      {
        return XcpImports.Application_GetVisualRoot() as UIElement;
      }
      [SecuritySafeCritical] set
      {
        XcpImports.CheckThread();
        if (value == null || !XcpImports.DependencyObject_IsPointerValid((DependencyObject) value))
          throw new InvalidOperationException(Resx.GetString("Application_InvalidRootVisual"));
        XcpImports.Application_SetVisualRoot(value);
        this._rootVisual = value;
      }
    }

    public Window MainWindow
    {
      get
      {
        if (!Application.Current.IsRunningOutOfBrowser)
          throw new NotSupportedException(Resx.GetString("Window_NotSupportedForInBrowser"));
        else
          return this._mainWindow;
      }
      internal set
      {
        this._mainWindow = value;
      }
    }

    public WindowCollection Windows
    {
      get
      {
        XcpImports.CheckThread();
        if (!Application.Current.IsRunningOutOfBrowser)
          throw new NotSupportedException(Resx.GetString("Window_NotSupportedForInBrowser"));
        else
          return this._windows;
      }
    }

    public IList ApplicationLifetimeObjects
    {
      get
      {
        XcpImports.CheckThread();
        return (IList) this.PrivateServiceCollection;
      }
    }

    public SilverlightHost Host
    {
      get
      {
        XcpImports.CheckThread();
        if (this._host == null)
          this._host = new SilverlightHost();
        return this._host;
      }
    }

    public InstallState InstallState
    {
      get
      {
        XcpImports.CheckThread();
        return (InstallState) XcpImports.GetValue((IManagedPeerBase) this, Application.InstallStateProperty);
      }
    }

    public bool IsRunningOutOfBrowser
    {
      get
      {
        XcpImports.CheckThread();
        return (bool) XcpImports.GetValue((IManagedPeerBase) this, Application.IsRunningOutOfBrowserProperty);
      }
    }

    public bool HasElevatedPermissions
    {
      get
      {
        return this._hasElevatedPermissions;
      }
      [EditorBrowsable(EditorBrowsableState.Never), SecurityCritical] set
      {
        XcpImports.Application_SetHasElevatedPermissions(value);
        this._hasElevatedPermissions = value;
      }
    }

    internal bool ApplicationStarted
    {
      get
      {
        XcpImports.CheckThread();
        return (bool) XcpImports.GetValue((IManagedPeerBase) this, Application.ApplicationStartedProperty);
      }
    }

    ApplicationLifetimeObjectsCollection PrivateServiceCollection
    {
      private get
      {
        if (this._collection == null)
          this._collection = new ApplicationLifetimeObjectsCollection();
        return this._collection;
      }
    }

    internal bool AllowNavigation
    {
      get
      {
        if (!this._allowNavigation.HasValue)
          this._allowNavigation = new bool?(XcpImports.Application_GetAllowNavigation());
        return this._allowNavigation.Value;
      }
    }

    public static Application Current
    {
      [SecuritySafeCritical] get
      {
        if (Application._current != null)
          return Application._current;
        IntPtr pApp;
        XcpImports.Application_GetCurrent(out pApp);
        if (!(pApp != IntPtr.Zero))
          return (Application) null;
        Application application = (Application) ManagedPeerTable.EnsureManagedPeer(pApp, 0, typeof (Application));
        XcpImports.ReleaseNativeObject(ref pApp);
        return application;
      }
    }

    public event StartupEventHandler Startup
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20052U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20052U, (Type) null), (Delegate) value);
      }
    }

    public event EventHandler Exit
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20053U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20053U, (Type) null), (Delegate) value);
      }
    }

    public event EventHandler<ApplicationUnhandledExceptionEventArgs> UnhandledException
    {
      add
      {
        XcpImports.CheckThread();
        this._appUnhandledException = this._appUnhandledException + value;
      }
      remove
      {
        XcpImports.CheckThread();
        if (this._appUnhandledException == null)
          return;
        this._appUnhandledException = this._appUnhandledException - value;
      }
    }

    public event EventHandler InstallStateChanged
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20058U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20058U, (Type) null), (Delegate) value);
      }
    }

    public event CheckAndDownloadUpdateCompletedEventHandler CheckAndDownloadUpdateCompleted
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20059U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20059U, (Type) null), (Delegate) value);
      }
    }

    private event StartupEventHandler Starting
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20054U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20054U, (Type) null), (Delegate) value);
      }
    }

    private event EventHandler Started
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20055U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20055U, (Type) null), (Delegate) value);
      }
    }

    private event EventHandler Exiting
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20056U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20056U, (Type) null), (Delegate) value);
      }
    }

    private event EventHandler Exited
    {
      add
      {
        XcpImports.CheckThread();
        this.AddEventListener(DependencyProperty.RegisterCoreProperty(20057U, (Type) null), (Delegate) value);
      }
      remove
      {
        XcpImports.CheckThread();
        this.RemoveEventListener(DependencyProperty.RegisterCoreProperty(20057U, (Type) null), (Delegate) value);
      }
    }

    static Application()
    {
    }

    public Application()
      : this(83U)
    {
    }

    [SecuritySafeCritical]
    internal Application(uint nativeTypeIndex)
    {
      Application._current = this;
      IntPtr num = IntPtr.Zero;
      IntPtr objectByTypeIndex = XcpImports.CreateObjectByTypeIndex(nativeTypeIndex);
      this.m_nativePtr = new NativeObjectSafeHandle();
      this.m_nativePtr.NativeObject = objectByTypeIndex;
      ManagedPeerTable.Add(objectByTypeIndex, (IManagedPeerBase) this);
      this._coreTypeEventHelper = new CoreTypeEventHelper();
      bool isCustomType = !TypeProxy.IsCoreType(this.GetType());
      XcpImports.NotifyHasManagedPeer(objectByTypeIndex, 11, isCustomType);
      this._hasElevatedPermissions = XcpImports.Application_GetHasElevatedPermissions();
      Deployment current = Deployment.Current;
      this._windows = new WindowCollection();
      this.Starting += new StartupEventHandler(this.Application_Starting);
      this.Started += new EventHandler(this.Application_Started);
      this.Exiting += new EventHandler(this.Application_Exiting);
      this.Exited += new EventHandler(this.Application_Exited);
    }

    [SecurityCritical]
    void IManagedPeer.BeginShutdown()
    {
      GC.SuppressFinalize((object) this.m_nativePtr);
      XcpImports.DisconnectManagedPeer((IManagedPeerBase) this);
    }

    [SecurityCritical]
    void IManagedPeer.EndShutdown()
    {
      XcpImports.ReleaseNativeObject((IManagedPeerBase) this);
      this.m_nativePtr = (NativeObjectSafeHandle) null;
    }

    [SecurityCritical]
    void IManagedPeer.RemovePeerReferenceToItem(IManagedPeerBase child)
    {
      this._treeChildren.Remove(child);
    }

    [SecurityCritical]
    void IManagedPeer.AddPeerReferenceToItem(IManagedPeerBase child)
    {
      if (this._treeChildren == null)
        this._treeChildren = new Dictionary<IManagedPeerBase, object>(1);
      this._treeChildren[child] = (object) null;
    }

    Delegate IManagedPeer.GetInstanceEventDelegate(string eventName)
    {
      return this._coreTypeEventHelper.GetInstanceEventDelegate(eventName);
    }

    void IManagedPeer.SetPeerReferenceToProperty(uint nPropertyID, DependencyObject value)
    {
      throw new InvalidOperationException();
    }

    [SecuritySafeCritical]
    public bool Install()
    {
      if (!Application.Current.Host.Source.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) && !Application.Current.Host.Source.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) && !Application.Current.Host.Source.Scheme.Equals("file", StringComparison.OrdinalIgnoreCase))
        throw new InvalidOperationException(Resx.GetString("Application_CannotBeInstalled"));
      if (InstallState.Installed == this.InstallState)
        throw new InvalidOperationException(Resx.GetString("Application_AlreadyInstalled"));
      else
        return XcpImports.Application_Install(this, false);
    }

    public void CheckAndDownloadUpdateAsync()
    {
      XcpImports.Application_CheckAndDownloadUpdate(this);
    }

    private void Application_Starting(object sender, StartupEventArgs e)
    {
      List<object> list = new List<object>();
      this.StartMulticoreJit();
      this.PrivateServiceCollection.MakeReadOnly();
      this.MainWindow = this.GetApplicationWindow();
      foreach (IApplicationService applicationService in (IEnumerable) this.ApplicationLifetimeObjects)
      {
        if (applicationService != null)
        {
          try
          {
            applicationService.StartService(new ApplicationServiceContext());
          }
          catch (Exception ex)
          {
            if (Error.IsCriticalException(ex))
            {
              throw;
            }
            else
            {
              list.Add((object) applicationService);
              this._appUnhandledException((object) this, new ApplicationUnhandledExceptionEventArgs(ex, false));
            }
          }
        }
      }
      foreach (object obj in list)
        this.PrivateServiceCollection.RemoveItem(obj);
      foreach (IApplicationService applicationService in (IEnumerable) this.ApplicationLifetimeObjects)
      {
        if (applicationService is IApplicationLifetimeAware)
        {
          IApplicationLifetimeAware applicationLifetimeAware = (IApplicationLifetimeAware) applicationService;
          try
          {
            applicationLifetimeAware.Starting();
          }
          catch (Exception ex)
          {
            if (Error.IsCriticalException(ex))
              throw;
            else
              this._appUnhandledException((object) this, new ApplicationUnhandledExceptionEventArgs(ex, false));
          }
        }
      }
      this.Startup += (StartupEventHandler) ((s, a) => XcpImports.Application_RequestStartedEvent(this));
      XcpImports.Application_RequestStartupEvent(this);
    }

    private void Application_Started(object sender, EventArgs e)
    {
      foreach (IApplicationService applicationService in (IEnumerable) this.ApplicationLifetimeObjects)
      {
        if (applicationService is IApplicationLifetimeAware)
        {
          IApplicationLifetimeAware applicationLifetimeAware = (IApplicationLifetimeAware) applicationService;
          try
          {
            applicationLifetimeAware.Started();
          }
          catch (Exception ex)
          {
            if (Error.IsCriticalException(ex))
              throw;
            else
              this._appUnhandledException((object) this, new ApplicationUnhandledExceptionEventArgs(ex, false));
          }
        }
      }
    }

    private void Application_Exiting(object sender, EventArgs e)
    {
      this.Host.OnApplicationExiting();
      NotificationWindow current = NotificationWindow.Current;
      if (current != null)
        current.Close();
      foreach (IApplicationService applicationService in (IEnumerable) this.ApplicationLifetimeObjects)
      {
        if (applicationService is IApplicationLifetimeAware)
        {
          IApplicationLifetimeAware applicationLifetimeAware = (IApplicationLifetimeAware) applicationService;
          try
          {
            applicationLifetimeAware.Exiting();
          }
          catch (Exception ex)
          {
            if (Error.IsCriticalException(ex))
              throw;
            else
              this._appUnhandledException((object) this, new ApplicationUnhandledExceptionEventArgs(ex, false));
          }
        }
      }
    }

    private void Application_Exited(object sender, EventArgs e)
    {
      foreach (IApplicationService applicationService in (IEnumerable) this.ApplicationLifetimeObjects)
      {
        if (applicationService is IApplicationLifetimeAware)
        {
          IApplicationLifetimeAware applicationLifetimeAware = (IApplicationLifetimeAware) applicationService;
          try
          {
            applicationLifetimeAware.Exited();
          }
          catch (Exception ex)
          {
            if (Error.IsCriticalException(ex))
              throw;
            else
              this._appUnhandledException((object) this, new ApplicationUnhandledExceptionEventArgs(ex, false));
          }
        }
      }
      for (int index = this.ApplicationLifetimeObjects.Count - 1; index >= 0; --index)
      {
        try
        {
          IApplicationService applicationService = this.ApplicationLifetimeObjects[index] as IApplicationService;
          if (applicationService != null)
            applicationService.StopService();
        }
        catch (Exception ex)
        {
          this._appUnhandledException((object) this, new ApplicationUnhandledExceptionEventArgs(ex, false));
        }
      }
      this.CleanInBrowserAppDataCache();
    }

    [SecuritySafeCritical]
    public static void LoadComponent(object component, Uri resourceLocator)
    {
      XcpImports.CheckThread();
      Type componentType = (Type) null;
      uint hr = 0U;
      if (resourceLocator == (Uri) null)
        throw new ArgumentNullException("resourceLocator");
      if (component == null)
        throw new ArgumentNullException("component");
      if (!QuirksMode.ShouldUseSL3Parser())
      {
        componentType = component.GetType();
        RuntimeTypeHandle typeHandle = componentType.TypeHandle;
        if (typeHandle.Equals(typeof (Deployment).TypeHandle) || typeHandle.Equals(typeof (OutOfBrowserSettings).TypeHandle) || (typeHandle.Equals(typeof (WindowSettings).TypeHandle) || typeHandle.Equals(typeof (SecuritySettings).TypeHandle)) || typeHandle.Equals(typeof (Icon).TypeHandle))
          throw new ArgumentException("component");
      }
      if (resourceLocator.IsAbsoluteUri)
        throw new ArgumentException(Resx.GetString("Application_UriMustBeRelative"));
      if (Application.IsComponentUri(resourceLocator))
      {
        string partName = (string) null;
        string assemblyName = (string) null;
        string assemblyVersion = (string) null;
        string assemblyKey = (string) null;
        if (!QuirksMode.ShouldUseSL3Parser())
          ResourceManagerWrapper.GetAssemblyNameAndPart(resourceLocator, out partName, out assemblyName, out assemblyVersion, out assemblyKey);
        if (componentType == null)
          componentType = component.GetType();
        UnmanagedMemoryStream stream = ResourceManagerWrapper.GetResourceForUri(resourceLocator, componentType) as UnmanagedMemoryStream;
        if (stream != null)
        {
          uint numBytesToRead = (uint) stream.Length;
          hr = XcpImports.Application_LoadComponent((IManagedPeerBase) ManagedObjectReference.ConditionalWrap(component), resourceLocator.OriginalString, stream, numBytesToRead, assemblyName);
          stream.Close();
        }
      }
      else
        hr = XcpImports.Application_LoadComponent((IManagedPeerBase) ManagedObjectReference.ConditionalWrap(component), resourceLocator.OriginalString, (UnmanagedMemoryStream) null, 0U, string.Empty);
      if ((int) hr != 0)
        throw XamlParseException.CreateFromCore(hr);
    }

    public static StreamResourceInfo GetResourceStream(StreamResourceInfo zipPackageStreamResourceInfo, Uri uriResource)
    {
      Application current = Application.Current;
      if (current == null)
        throw new ArgumentException(Resx.GetString("Application_ApplicationNotInitialized"));
      else
        return current.GetResourceStreamInternal(zipPackageStreamResourceInfo, uriResource);
    }

    internal StreamResourceInfo GetResourceStreamInternal(StreamResourceInfo zipPackageStreamResourceInfo, Uri resourceUri)
    {
      StreamResourceInfo streamResourceInfo = (StreamResourceInfo) null;
      if (zipPackageStreamResourceInfo == null)
        throw new ArgumentNullException("zipPackageStreamResourceInfo");
      if (resourceUri == (Uri) null)
        throw new ArgumentNullException("resourceUri");
      if (resourceUri.IsAbsoluteUri)
        throw new ArgumentException(Resx.GetString("Application_ExpectedRelativeUri"));
      InternalMemoryStream stream1 = zipPackageStreamResourceInfo.Stream as InternalMemoryStream;
      if (stream1 != null)
      {
        Stream resourceStream = XcpImports.Application_GetResourceStream(this, stream1, resourceUri);
        if (resourceStream != null)
          streamResourceInfo = new StreamResourceInfo(resourceStream, (string) null);
      }
      else
      {
        Stream stream2 = zipPackageStreamResourceInfo.Stream;
        if (stream2 != null)
        {
          long position = stream2.Position;
          int count = (int) stream2.Length;
          int offset = 0;
          byte[] numArray = new byte[count];
          while (count > 0)
          {
            int num = stream2.Read(numArray, offset, count);
            if (num != 0)
            {
              offset += num;
              count -= num;
            }
            else
              break;
          }
          if (stream2.CanSeek)
            stream2.Seek(position, SeekOrigin.Begin);
          Stream resourceStream = XcpImports.Application_GetResourceStream(this, (uint) offset, numArray, resourceUri);
          if (resourceStream != null)
            streamResourceInfo = new StreamResourceInfo(resourceStream, (string) null);
        }
      }
      return streamResourceInfo;
    }

    public static StreamResourceInfo GetResourceStream(Uri uriResource)
    {
      Application current = Application.Current;
      if (current == null)
        throw new ArgumentException(Resx.GetString("Application_ApplicationNotInitialized"));
      else
        return current.GetResourceStreamInternal(uriResource);
    }

    [SecuritySafeCritical]
    internal StreamResourceInfo GetResourceStreamInternal(Uri resourceUri)
    {
      StreamResourceInfo streamResourceInfo = (StreamResourceInfo) null;
      if (resourceUri == (Uri) null)
        throw new ArgumentNullException("resourceUri");
      if (resourceUri.IsAbsoluteUri)
        throw new ArgumentException(Resx.GetString("Application_ExpectedRelativeUri"));
      Stream stream = !Application.IsComponentUri(resourceUri) ? XcpImports.Application_GetResourceFromApplication(this, resourceUri) : ResourceManagerWrapper.GetResourceForUri(resourceUri) as Stream;
      if (stream != null)
        streamResourceInfo = new StreamResourceInfo(stream, (string) null);
      return streamResourceInfo;
    }

    private static bool IsComponentUri(Uri xamlUri)
    {
      string str1 = xamlUri.ToString();
      bool flag = false;
      string str2 = string.Empty;
      int startIndex = 0;
      if ((int) str1[0] == 47)
        startIndex = 1;
      int num = str1.IndexOf('/', startIndex);
      if (num > 0 && str1.Substring(startIndex, num - startIndex).EndsWith(";component", StringComparison.OrdinalIgnoreCase))
        flag = true;
      return flag;
    }

    internal static Dictionary<string, string> ParseInitParams()
    {
      Dictionary<string, string> dictionary = new Dictionary<string, string>();
      string initParams = XcpImports.Application_GetInitParams();
      if (!string.IsNullOrEmpty(initParams))
      {
        string str1 = initParams;
        char[] chArray = new char[1]
        {
          ','
        };
        foreach (string str2 in str1.Split(chArray))
        {
          int length = str2.IndexOf('=');
          string index;
          string str3;
          if (length == -1)
          {
            index = str2.Trim();
            str3 = string.Empty;
          }
          else
          {
            index = str2.Substring(0, length).Trim();
            str3 = length < str2.Length - 1 ? str2.Substring(length + 1).Trim() : string.Empty;
          }
          if (index.Length != 0)
            dictionary[index] = str3;
        }
      }
      return dictionary;
    }

    [SecuritySafeCritical]
    private void StartMulticoreJit()
    {
      string str1 = "32";
      string str2 = "";
      bool doSetProfileRoot = false;
      bool doStartProfile = false;
      StringBuilder stringBuilder1 = new StringBuilder("");
      bool runningOutOfBrowser = this.IsRunningOutOfBrowser;
      Type type = Type.GetType("System.Runtime.ProfileOptimization", false);
      if (type == null)
        return;
      this.ShouldSetupMulticoreJit(out doSetProfileRoot, out doStartProfile);
      if (doSetProfileRoot)
      {
        string path;
        if (runningOutOfBrowser)
        {
          string appIDStr = (string) null;
          string xapLocationStr = (string) null;
          try
          {
            XcpImports.Application_GetAppLocationAndID(out appIDStr, out xapLocationStr);
          }
          catch (Exception ex)
          {
            return;
          }
          path = xapLocationStr;
        }
        else
        {
          StringBuilder stringBuilder2 = new StringBuilder(Environment.UnsafeGetFolderPath(Environment.SpecialFolder.LocalApplicationData));
          if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6)
            stringBuilder2.Append("Low");
          stringBuilder2.AppendFormat("{0}Microsoft{0}Silverlight{0}InBrowser{0}Profiles", new object[1]
          {
            (object) Path.DirectorySeparatorChar
          });
          path = ((object) stringBuilder2).ToString();
          if (!Directory.UnsafeExists(path))
            Directory.UnsafeCreateDirectory(path);
        }
        type.InvokeMember("SetProfileRoot", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, (Binder) null, (object) null, new object[1]
        {
          (object) path
        });
      }
      if (!doStartProfile)
        return;
      if (!runningOutOfBrowser)
      {
        NativeHost current = NativeHost.Current;
        str2 = current == null ? "_default" : "_" + current.FinalSource.GetHashCode().ToString("X");
      }
      stringBuilder1.AppendFormat("Jit{0}{1}.profile", new object[2]
      {
        (object) str1,
        (object) str2
      });
      type.InvokeMember("StartProfile", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, (Binder) null, (object) null, new object[1]
      {
        (object) ((object) stringBuilder1).ToString()
      });
    }

    [SecuritySafeCritical]
    private void CleanInBrowserAppDataCache()
    {
      bool doSetProfileRoot = false;
      bool doStartProfile = false;
      int length = 0;
      IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>) new FileInfo[0];
      this.ShouldSetupMulticoreJit(out doSetProfileRoot, out doStartProfile);
      if (!doSetProfileRoot || this.IsRunningOutOfBrowser)
        return;
      StringBuilder stringBuilder = new StringBuilder(Environment.UnsafeGetFolderPath(Environment.SpecialFolder.LocalApplicationData));
      if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6)
        stringBuilder.Append("Low");
      stringBuilder.AppendFormat("{0}Microsoft{0}Silverlight{0}InBrowser{0}Profiles", new object[1]
      {
        (object) Path.DirectorySeparatorChar
      });
      string path = ((object) stringBuilder).ToString();
      using (new NativeHost.SandboxSecurityOverride())
      {
        if (Directory.UnsafeExists(path))
          enumerable = new DirectoryInfo(path).EnumerateFiles("*.profile");
        foreach (FileInfo fileInfo in enumerable)
          ++length;
        if (length <= 500)
          return;
        int num1 = length - 500;
        FileInfo[] items = new FileInfo[length];
        DateTime[] keys = new DateTime[length];
        int num2 = 0;
        foreach (FileInfo fileInfo in enumerable)
          items[num2++] = fileInfo;
        for (int index = 0; index < items.Length; ++index)
          keys[index] = items[index].LastWriteTime;
        Array.Sort<DateTime, FileInfo>(keys, items);
        foreach (FileInfo fileInfo in items)
        {
          try
          {
            fileInfo.Delete();
            if (--num1 == 0)
              break;
          }
          catch
          {
          }
        }
      }
    }

    [SecurityCritical]
    private void ShouldSetupMulticoreJit(out bool doSetProfileRoot, out bool doStartProfile)
    {
      doSetProfileRoot = false;
      doStartProfile = false;
      NativeHost current = NativeHost.Current;
      if (QuirksMode.ShouldAllowMulticoreJit() && XcpImports.Application_GetXapSize() >= 500000L && (!DesignerProperties.IsInDesignTool && current != null) && (current.BrowserService == null || !current.BrowserService.InPrivateMode()))
      {
        doSetProfileRoot = true;
        doStartProfile = true;
      }
      else
      {
        if (!QuirksMode.ShouldAllowMulticoreJit() || !this.HasElevatedPermissions)
          return;
        doSetProfileRoot = true;
      }
    }

    [SecuritySafeCritical]
    private Window GetApplicationWindow()
    {
      XcpImports.CheckThread();
      if (Application.Current.IsRunningOutOfBrowser)
      {
        try
        {
          return XcpImports.Application_GetWindow();
        }
        catch
        {
        }
      }
      return (Window) null;
    }

    [SecuritySafeCritical]
    private void AddEventListener(DependencyProperty property, Delegate handler)
    {
      object managedPeer = (object) null;
      if (!ManagedPeerTable.TryGetManagedPeer(this.m_nativePtr.NativeObject, out managedPeer))
        ManagedPeerTable.Add(this.m_nativePtr.NativeObject, (IManagedPeerBase) this);
      this._coreTypeEventHelper.AddEventListener((IManagedPeer) this, property, handler);
    }

    private void RemoveEventListener(DependencyProperty property, Delegate handler)
    {
      this._coreTypeEventHelper.RemoveEventListener((IManagedPeer) this, property, handler);
    }
  }
}
